from http.client import responses

from django.db.models.expressions import result
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
# Create your views here.
from elasticsearch_dsl import Q as ESQ
from rest_framework.response import Response

from search.documents.course import CourseIndex


class CoursePagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 50


class CourseSearchView(ListAPIView):
    pagination_class = CoursePagination

    def get_queryset(self):
        nav_name = self.request.query_params.get('nav_name')
        cate = self.request.query_params.get('cate')
        keyword = self.request.query_params.get('keyword')
        ids = self.request.query_params.get('ids')
        sort_ord = self.request.query_params.get('sort')
        price_range = self.request.query_params.get('price')
        s = CourseIndex.search()
        s.filter('term', status=1)
        if nav_name:
            s = s.filter('term', nav_category_names=nav_name)
        if cate:
            s = s.filter('term', category_ids=cate)
        if price_range:
            type_price = int(price_range)
            s = s.filter('term', course_type=type_price)
        if keyword:
            s = s.query(ESQ("multi_match", query=keyword, fields=['name^10', 'brief^5', 'teacher_name']))
            s = s.highlight_options(
                pre_tags=["<span class='highlight'>"],  # 高亮开始标签
                post_tags=['</span>'],  # 高亮结束标签
                number_of_fragments=0  # 返回完整字段而不是片段
            )
            s = s.highlight("name", "brief", "teacher_name")

        if sort_ord:
            s = s.sort(sort_ord)
        if ids:
            ids_list = ids.split(',')
            s = s.filter('terms', id=ids_list)
        if not any([nav_name, cate, keyword, sort_ord, price_range]):
            s = s.query('match_all')
        response = s.execute()
        results = []
        for hit in response:
            course_dic = hit.to_dict()
            hit['teacher'] = {
                'name': hit['teacher_name'],
                'title': hit['teacher_title'],
                'id': hit['teacher_id'],
            }

            if hasattr(hit.meta, 'highlight'):
                # 先设置一个空字典
                highlight = {}
                # 去判断是name  brief  teacher_name 中的哪一个有高亮
                if hasattr(hit.meta.highlight, "name"):
                    highlight["name"] = hit.meta.highlight["name"][0]
                if hasattr(hit.meta.highlight, "brief"):
                    highlight["brief"] = hit.meta.highlight["brief"][0]
                if hasattr(hit.meta.highlight, "teacher_name"):
                    highlight["teacher_name"] = hit.meta.highlight["teacher_name"][0]
                # 将高亮的数据添加到字典中
                course_dic["highlight"] = highlight
            results.append(course_dic)
        return results

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            return self.get_paginated_response(page)
        return Response(queryset)
